# THIS FILE IS A PART OF VCStudio
# PYTHON 3

# This a console project manager.

import os
import time

# GTK module ( Graphical interface
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gdk
import cairo

# Own modules
from settings import settings
from settings import talk
from settings import fileformats
from project_manager import pm_project

#UI modules
from UI import UI_elements
from UI import UI_color

# story
from studio import story
from studio import analytics
from studio import history

def layer(win, call):
    
    # Making the layer
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, win.current['w'],
                                                      win.current['h'])
    layer = cairo.Context(surface)
    
    
    #text setting
    layer.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    
    UI_color.set(layer, win, "dark_overdrop")
    layer.rectangle(
        0,
        0,
        win.current["w"],
        win.current["h"],
        )
    layer.fill()
    
    
    
    UI_color.set(layer, win, "node_background")
    UI_elements.roundrect(layer, win, 
        80,
        80,
        win.current["w"]-160,
        win.current["h"]-160,
        10)
    
    ############################################################################
    
    # Before we start anything. I would like to refresh the cash of the assets.
    # so I would have the most up to date list / fractions of each item.
    
    # In the studio/story.py there is the get_asset_data() functions. Which if
    # you look closly just loads fraction into a dictionary called win.assets
    # from which we can read directly. 
    
    # The function is designed to give load the fraction ones and then just give
    # you one from the RAM. So it's not always going to read the asset.progress
    # files which is not too good. Since I want to have a good idea about the 
    # asset's actuall fraction. 
    
    # One way I can force it to update is by using the force argument. But doing
    # it on every frame defeats the purpose of the function entirelly. So here
    # what I'm going to do. Each time I close this window. AKA return anything
    # I am also going to wipe the dictionary win.asset clean. It will take one
    # frame of potential lag to load everything back ( at least the stuff that's
    # ont the screen in a given moment. 
    
    # Also to make sure that this dialog has the up to date info. I will do it
    # as well in the studio_dialogs.py when initilizing this function. So yeah.
    
    # Let's continue with the program.
    
    ############################################################################
    
    
    
    
    ####### TOP PANEL #######
    
    for num, cur in enumerate(["chr","veh","loc","obj"]):
        
        if win.current["asset_cur"] == cur:
            
            UI_color.set(layer, win, "progress_time")
            UI_elements.roundrect(layer, win,
                100+(40*num),
                100, 
                40,
                40,
                10)
        
        def do():
            win.current["asset_cur"] = cur
        
        UI_elements.roundrect(layer, win,
            100+(40*num),
            100, 
            40,
            40,
            10,
            do,
            cur,
            tip=talk.text(cur))
    
    # In case the user is confused
    UI_color.set(layer, win, "text_normal")
    layer.set_font_size(30)
    layer.move_to(300,130)
    layer.show_text(talk.text(win.current["asset_cur"]))
    
    
    # Search
    
    UI_elements.image(layer, win, "settings/themes/"\
        +win.settings["Theme"]+"/icons/search.png", 
        win.current["w"]-440,
        100, 
        40,
        40)
    
    UI_elements.text(layer, win, "asset_select_search",
        win.current["w"]-400,
        100,
        250,
        40)
    
    # CANCEl
    
    def do():
        win.current["calls"][call]["var"] = False 
        win.assets = {}
        
    UI_elements.roundrect(layer, win, 
        win.current["w"]-120,
        win.current["h"]-120,
        40,
        40,
        10,
        button=do,
        icon="cancel",
        tip=talk.text("cancel"))
    
    # Short cut ESC
    if 65307 in win.current["keys"] and not win.textactive:
        do()    
    
     # Now let's prepare the ground for the next part. 
    
    UI_elements.roundrect(layer, win, 
        100,
        150,
        win.current["w"]-200,
        win.current["h"]-250,
        10,
        fill=False)
    layer.clip()
    
    
    
    tileX = 120
    current_Y = 50
    
    if "asset_select" not in win.scroll:
        win.scroll["asset_select"] = 0
    
    newcreate = win.text["asset_select_search"]["text"].replace("/","_").replace(" ", "_")\
    .replace('"',"_").replace("(","_").replace(")","_").replace("'","_")\
    .replace("[","_").replace("]","_").replace("{","_").replace("}","_")
    
    ###########################
    okay = True
    
    for asset in os.listdir(win.project+"/dev/"+win.current["asset_cur"]):
        if os.path.isdir(win.project+"/dev/"+win.current["asset_cur"]+"/"+asset):
            
            okay = True
            
            # Search            
            
            if win.text["asset_select_search"]["text"]\
            and newcreate.lower() not in asset.lower():
                okay = False
            
            if okay:
                
                
                if int(current_Y + win.scroll["asset_select"] + 100) in range(0-100, win.current["h"]):
                    
                    # Making the layer
                    nodesurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 170, 200)
                    node = cairo.Context(nodesurface)
                    node.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
                    
                    
                    UI_elements.roundrect(node, win, 
                        0,
                        0,
                        170,
                        200,
                        10,
                        fill=False)
                    
                    node.clip()
                    
                    # Background
                    UI_color.set(node, win, "dark_overdrop")
                    node.rectangle(0,0,170, 200)
                    node.fill()
                    
                    # Banner
                    UI_color.set(node, win, "node_asset") 
                    node.rectangle(0,0,170, 20)
                    node.fill()
                    
                    # Outputting the layer
                    layer.set_source_surface(nodesurface, 
                            tileX-10,
                            current_Y + win.scroll["asset_select"] + 120)
                    layer.paint()
                    
                    
                    # Previes image
                    
                    if os.path.exists(win.project+"/dev/"+win.current["asset_cur"]+"/"+asset+"/renders/Preview.png"):
                        UI_elements.image(layer, win, win.project+"/dev/"+win.current["asset_cur"]+"/"+asset+"/renders/Preview.png", 
                            tileX,
                            current_Y + win.scroll["asset_select"] + 140, 
                            150,
                            150)
                    
                    elif os.path.exists(win.project+"/dev/"+win.current["asset_cur"]+"/"+asset+"/renders/Preview.jpg"):
                        UI_elements.image(layer, win, win.project+"/dev/"+win.current["asset_cur"]+"/"+asset+"/renders/Preview.jpg", 
                            tileX,
                            current_Y + win.scroll["asset_select"] + 140, 
                            150,
                            150)
                    else:
                        UI_elements.image(layer, win, "settings/themes/"+win.settings["Theme"]+"/icons/"+win.current["asset_cur"]+".png", 
                            tileX+55,
                            current_Y + win.scroll["asset_select"] + 150+55, 
                            150,
                            150)
                    
                    # Progress bar
                    
                    fraction = story.get_asset_data(win, win.current["asset_cur"]+"/"+asset)["fraction"]
            
                    UI_color.set(layer, win, "progress_background")
                    UI_elements.roundrect(layer, win,
                        tileX,
                        current_Y + win.scroll["asset_select"] + 300, 
                        150,
                        0,
                        5)
                    
                    UI_color.set(layer, win, "progress_active")
                    UI_elements.roundrect(layer, win,
                        tileX,
                        current_Y + win.scroll["asset_select"] + 300, 
                        150*fraction,
                        0,
                        5)
                    
                    UI_color.set(layer, win, "text_normal")
                    layer.set_font_size(12)
                    layer.move_to(tileX,
                        current_Y + win.scroll["asset_select"] + 135)
                    layer.show_text(asset[asset.rfind("/")+1:][:22])   
                    
                    
                    
                    
                    
                        
                    
                    
                    # Button to activate it
                    def do():
                        win.current["calls"][call]["var"] = "/"+win.current["asset_cur"]+"/"+asset
                        win.assets = {}
                        
                        
                        
                    layer.set_line_width(4)    
                    UI_elements.roundrect(layer, win, 
                        tileX-10,
                        current_Y + win.scroll["asset_select"] + 120,
                        170,
                        200,
                        10,
                        button=do,
                        tip=talk.text(win.current["asset_cur"])+": "+asset,
                        fill=False,
                        clip=[
                                100,
                                150,
                                win.current["w"]-200,
                                win.current["h"]-250
                                ])
                    
                    layer.stroke()
                    layer.set_line_width(2)
                
                tileX += 200
                
                if tileX > win.current["w"]-270:
                    tileX = 120
                    
                    current_Y += 230
    
    
    
    if win.text["asset_select_search"]["text"]\
    and newcreate\
    not in os.listdir(win.project+"/dev/"+win.current["asset_cur"])\
    and newcreate not in "chr veh loc obj": #Avoiding potential mistakes
        
        # If there is a seach and there is no asset with the search name. It
        # will ask if you want to create such an asset.
        
        def do():
            
            # I don't thing I need to write a whole module for creating a couple
            # of folders. 
             
            try:
                os.mkdir(win.project+"/dev/"+win.current["asset_cur"]+"/"+newcreate)
                os.mkdir(win.project+"/dev/"+win.current["asset_cur"]+"/"+newcreate+"/renders")
                os.mkdir(win.project+"/dev/"+win.current["asset_cur"]+"/"+newcreate+"/reference")
                os.mkdir(win.project+"/dev/"+win.current["asset_cur"]+"/"+newcreate+"/tex")
                
                # Recodring to history
                history.record(win, win.project+"/dev/"+win.current["asset_cur"]+"/"+newcreate, "[Added Asset]")
                
            except:
                pass
            
            
            # There is a problem that was introduced with the multiuser.
            # Basically. The other user whould need to create this asset too. And it's
            # not cool. I want to the experience to be seamless. Or at least somewhat seamless.
            
            # So I'm going to enter the cur of the asset for a fraction of a second. And then 
            # come back to what ever we were doing.
            tmp = win.cur
            win.cur = win.current["asset_cur"]
            time.sleep(0.1) # This should be plenty
            win.cur = tmp
            
            
            win.text["asset_select_search"]["text"] = ""
            
            win.current["calls"][call]["var"] = "/"+win.current["asset_cur"]+"/"+newcreate
            win.assets = {}
            
            
            # Refrashing analytics
            win.analytics    = analytics.load(win.project)
            analytics.save(win.project, win.analytics)
            
        UI_elements.roundrect(layer, win, 
            tileX-10,
            current_Y + win.scroll["asset_select"] + 120,
            170,
            200,
            10,
            button=do,
            tip=talk.text("create_new_asset")+" "+newcreate)
        
        UI_color.set(layer, win, "progress_background")
        UI_elements.roundrect(layer, win, 
            tileX-10,
            current_Y + win.scroll["asset_select"] + 120,
            170,
            200,
            10,
            fill=False)
        layer.stroke()
        
        UI_elements.image(layer, win, 
            "settings/themes/"+win.settings["Theme"]+"/icons/asset_new.png",
            tileX+55,
            current_Y + win.scroll["asset_select"] + 200,
            40, 40)
        
        UI_color.set(layer, win, "text_normal")
        layer.set_font_size(12)
        layer.move_to(tileX+85-len(newcreate)*4,
            current_Y + win.scroll["asset_select"] + 300)
        layer.show_text(newcreate)
        
        
    
    ###########################
    
    current_Y += 230
    
    UI_elements.scroll_area(layer, win, "asset_select", 
        50,
        100,
        win.current["w"]-100,
        win.current["h"]-200,
        current_Y,
        bar=True,
        mmb=True,
        url="asset_select",
        strenght=130
        )
    
    
    
    return surface
